import os
import json
import time
import sys
from datetime import datetime
from datetime import timedelta
from datetime import timezone


def print_json(data):
    print(json.dumps(data, sort_keys=True, indent=4,
          separators=(', ', ': '), ensure_ascii=False))


SHA_TZ = timezone(
    timedelta(hours=8),
    # timedelta(hours=0),
    name='Asia/Shanghai',
)


def get_beijing_time():
    utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
    beijing_now = utc_now.astimezone(SHA_TZ)
    # beijing_now=beijing_now.strftime("%Y-%m-%d %H:%M:%S")
    print('get beijing time: ',beijing_now.strftime("%Y-%m-%d %H:%M:%S"))
    beijing_now = beijing_now.strftime("%Y-%m-%d")
    return beijing_now


def del_file(file_path):
    result = False
    if os.path.exists(file_path) == False:
        result = True
    else:
        for i in range(3):
            try:
                os.system('rm -r %s' % (file_path))
                result = True
                break
            except Exception as e:
                print('del %s error' % (file_path))
                print(e)
                time.sleep(0.1)
    # result &= (~os.path.exists(file_path))
    if os.path.exists(file_path):
        result &= False
    print('del %s: %s' % (file_path, str(result)))
    return result


def get_time_file():
    del_file('Hong_Kong')
    time.sleep(0.5)
    for i in range(3):
        try:
            os.system('wget http://worldtimeapi.org/api/timezone/Asia/Hong_Kong')
            time.sleep(0.1)
            break
        except Exception as e:
            pass
    return os.path.exists('Hong_Kong')


def take_time():
    times = {}
    if get_time_file():
        try:
            with open('Hong_Kong') as fr:
                times = json.load(fr)
                fr.close()
                times['day'] = times['utc_datetime'][:10]
                times['times'] = times['utc_datetime'][11:19]
        except Exception as e:
            print(e)
        print_json(times)
    return times


def set_time():
    result = False
    times = take_time()
    time_value = str(times['day'])+' '+str(times['times'])
    cmd = "timedatectl set-time \"%s\"" % (time_value)
    # print(cmd)
    for i in range(3):
        try:
            os.system('timedatectl set-ntp no')
            os.system(cmd)
            os.system('timedatectl set-ntp yes')
            break
        except Exception as e:
            print(e)
    if str(get_beijing_time()) == times['day']:
        result = True
    else:
        print('************time set filed**************')
    return result


if __name__ == '__main__':
    set_time()
    # take_time()
